package tweeks.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.util.DigestUtils;

public class ExTokenBasedRememberMeServices extends TokenBasedRememberMeServices {
	private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();
	
	public HttpServletRequest getContext() {
		return requestHolder.get();
	}
	
	public void setContext(HttpServletRequest context) {
		requestHolder.set(context);
	}
	
	protected String getUserIpAddress(HttpServletRequest request) {
		return request.getRemoteAddr();
	}
	
	@Override
	public void onLoginSuccess(HttpServletRequest request,
			HttpServletResponse response,
			Authentication successfulAuthentication) {
		try {
			setContext(request);
			super.onLoginSuccess(request, response, successfulAuthentication);
		} finally {
			setContext(null);
		}
	}
	
	@Override
	protected String makeTokenSignature(long tokenExpiryTime, String username,
			String password) {
		String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey() + ":" + getUserIpAddress(getContext());
//        MessageDigest digest;
//        try {
//            digest = MessageDigest.getInstance("MD5");
//        } catch (NoSuchAlgorithmException e) {
//            throw new IllegalStateException("No MD5 algorithm available!");
//        }
//        return new String(Hex.encode(digest.digest(data.getBytes())));
		return DigestUtils.md5DigestAsHex(data.getBytes());
	}
	
	@Override
	protected void setCookie(String[] tokens, int maxAge,
			HttpServletRequest request, HttpServletResponse response) {
		super.setCookie(tokens, maxAge, request, response);
	}
}
